package com.ay.weixin.fdc.front.usercenter.event.share;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;

import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.UserStatus;
import com.ay.weixin.config.types.UserType;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.FDCUserCenter;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashFlow;
import com.ay.weixin.fdc.front.usercenter.event.UserEvent;
import com.ay.weixin.fdc.front.usercenter.event.UserInfoAccess;

/**
 * 
 * 注册数据一天只能post 成功1次
 * 
 * */
public class ShareRegister extends Event implements Before{
	private FDCAgentDao user_dao;
	private IbatisCashFlow cash_dao;
	private UserEvent user_event;
	private UserInfoAccess user_access;
	private FDCUserCenter user_center;
	
	@Override
	public void init_property() throws Exception {
		
		user_dao=Container.get(FDCAgentDao.class);
		cash_dao=Container.get(IbatisCashFlow.class);
		user_event=Container.get(UserEvent.class);
		user_access=Container.get(UserInfoAccess.class);
		user_center=Container.get(FDCUserCenter.class);
		
	}

	
	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		bl.setAttr("user_type",UserType.share.name());
	}
	
	@Override
	public String default_handling_path() {
		return "/share/register/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long wxproject_id=el.queryPathInt(2);
		
		if(!el.getBool("is_weixin")&&ProjectConfig._bool(wxproject_id,"sys.weixin_only")){
			el.text("invalid visit");
			return;
		}
		if(el.getSessionAttr("user")!=null){
			el.response_to_root("/share/"+wxproject_id);
			return;
		}
		//微信授权
		UserWeiXinInfo weixin_info=el.getSessionAttr("weixin_info",UserWeiXinInfo.class);
		if(weixin_info==null){
			user_access.open_id_check(el,"/share/register/",wxproject_id);
			return;
		}
		
		UserBasic user=null;
		try {
			user=user_dao.getById(weixin_info.getUser_id());
		} catch (SQLException e) {
			e.printStackTrace();
			view(el,wxproject_id);
			return;
		}
		
		if(user!=null){
			el.setSessionAttr("user",user);
			user_center.setSession(user.getId(), el.getSession());
			el.response_to_root("/share/"+wxproject_id);
			return;
		}
		
		try_register(el,wxproject_id);
	}
	
	private void try_register(EventLoader el,long wxproject_id) throws IOException, ServletException{
		if(el.queryPathCheck(3,"submit")){
			submit(el,wxproject_id);
		}else{
			view(el,wxproject_id);
		}
	}
	
	private void view(EventLoader el,long wxproject_id) throws IOException, ServletException{
		UserEvent.load_vcode_check(el,wxproject_id);
		el.template("/WEB-INF/template/app/"+wxproject_id+"/share/register.vm");
	}
	
	private void submit(EventLoader el,long wxproject_id) throws IOException, ServletException{
		
		UserEvent.inc_vcode_check(el,wxproject_id);
		String name=el.getStr("name");
		String phone=el.getStr("phone");
		String vcode=el.getStr("vcode");
		String msg=null;
		boolean need_vcode=el.getSessionAttr("tel_vcode", 0)>=ProjectConfig.getInt(wxproject_id,"fdc_usercenter.vcode_used_error_in_times");
		if(need_vcode&&el.getSessionAttr("vcode")!=null&&!StringHelper.equals(vcode.toLowerCase(), el.getSessionAttr("vcode").toString().toLowerCase())){
			msg=el.i18("login.vcode_invalid");
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(name)||name.length()>Keys.getInt("fdc_usercenter.register_name_max_length")||name.length()<Keys.getInt("fdc_usercenter.register_name_min_length")){
			msg=String.format(el.i18("fdc_usercenter.name.not.valid"), Keys.getInt("fdc_usercenter.register_name_min_length"),Keys.getInt("fdc_usercenter.register_name_max_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
	
		if(StringHelper.isNull(phone)){
			msg=String.format(el.i18("fdc_usercenter.phone.not.valid"), Keys.getInt("fdc_usercenter.register_phone_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		try {
			if(user_dao.phoneExists(wxproject_id,phone)){
				msg=el.i18("fdc_usercenter.phone.already.exists");
				el.setAttr("msg",msg);
			    view(el,wxproject_id);
				return;
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
			el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
	        view(el,wxproject_id);
			return;
		}
		
		FDCAgent user=new FDCAgent();
		user.setName(name);
		user.setPhone(phone);
		user.setType(UserType.share.name());
		user.setStatus(UserStatus.ok.name());
		user.setCreate_time(new Date(System.currentTimeMillis()));
		user.setWxproject_id(wxproject_id);
		try{
			user_dao.insert(user);
			user=user_dao.getByPhone(wxproject_id,phone);
		}catch(Exception e){
			e.printStackTrace();
			el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
	        view(el,wxproject_id);
			return;
		}
		
		el.setSessionAttr("user",user);
		UserEvent.clean_vcode(el);
		UserEvent.setSessionTimeOut(el);
		el.setSessionAttr("registered",true);
		user_event.update_weixin(el,user.getId());
		user_center.setSession(user.getId(), el.getSession());
		el.response_to_root("/share/"+wxproject_id);
	}
	
	
	
}
